// payment_controller.dart
import 'dart:async';
import 'dart:convert';
import 'dart:io';

import 'package:bit_fury/http/http_agent.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:in_app_purchase_storekit/in_app_purchase_storekit.dart';
import 'package:in_app_purchase_storekit/store_kit_wrappers.dart';

import '../model/base_response.dart';
import '../model/contract_list_model.dart';
import '../service/analytics_service.dart';
import '../service/payment_service.dart';
import '../service/user_storage_service.dart';
import 'home_controller.dart';

/// 统一错误
class IapFailure {
  final String code;
  final String message;
  final dynamic details;
  final StackTrace? stack;
  const IapFailure(this.code, this.message, {this.details, this.stack});
  @override
  String toString() =>
      'IapFailure(code=$code, message=$message, details=$details)';
}

class PaymentController extends GetxController {
  // ===== 基础依赖 =====
  final InAppPurchase _iap = InAppPurchase.instance;
  final PaymentService _paymentService = PaymentService();
  late final StreamSubscription<List<PurchaseDetails>> _subscription;

  // ===== 状态 =====
  final RxList<ProductDetails> _products = <ProductDetails>[].obs;
  final RxBool _isAvailable = false.obs;
  final RxBool _purchasePending = false.obs;
  final RxBool _loading = true.obs;
  final RxString _queryProductError = ''.obs;

  bool _isRestoringPurchases = false;

  // // 全局购买 loading 控制
  bool _globalDialogShowing = false;
  Future<void>? _dialogFuture;
  // 等待服务器验证的订单集合（key 为 currentOrderId 或 purchaseKey）
  final Set<String> _pendingServerVerifications = <String>{};
// 可配置的验证超时时长
  static const Duration _verifyTimeout = Duration(seconds: 30);

  // ===== 订单态 =====
  final Rx<String?> currentOrderId = Rx<String?>(null);
  final Rx<PaidContract?> currentContract = Rx<PaidContract?>(null);
  final Rx<Function(bool)?> purchaseCallback = Rx<Function(bool)?>(null);
  bool _isBuying = false; // 防抖

  // ===== 幂等控制 =====
  final Set<String> _handledPurchases = <String>{}; // 已处理（成功/失败/取消都记一次）
  final Set<String> _completedPurchases =
      <String>{}; // 已 completePurchase 的 key

  // ===== 配置 =====
  static const List<String> _googleProductIds = <String>[
    'basic_plan', //4.9
    'pro_plan', // 9.9
    'elite_plan', //19.9
    'prime_plan', //49.9
    'ultra_plan', //99.9
    'infinity_plan', //199.9
    "quantum_plan" // 299.9
  ];

  static const List<String> _appleProductIds = <String>[
    // 'basic_plan_apple', //4.9
    // 'pro_plan_apple', // 9.9
    // 'elite_plan_apple', //19.9
    // 'prime_plan_apple', //49.9
    // 'ultra_plan_apple', //99.9
    // 'infinity_plan_apple', //199.9
    // "quantum_plan_apple" // 299.9
    "basic_plan_apple", //4.99
    "pro_plan_product", //9.99
    "elite_plan_product", //12.99
    "prime_plan_product", //17.99
    "ultra_plan_product", //19.99
    "infinity_plan_product", //24.99
    "quantum_plan_product" // 29.99
  ];

  /// 如果需要 Apple Server-to-Server 校验，填你的共享密钥；否则保持空字符串
  static const String _appStoreSharedSecret = '';

  // ===== 对外只读 =====
  List<ProductDetails> get products => _products;
  bool get isAvailable => _isAvailable.value;
  bool get purchasePending => _purchasePending.value;
  bool get loading => _loading.value;
  String get queryProductError => _queryProductError.value;

  // ===== 生命周期 =====
  @override
  void onInit() {
    super.onInit();

    // 监听购买更新流（单点入口）
    _subscription = _iap.purchaseStream.listen(
      _onPurchasesUpdated,
      onError: (Object error, [StackTrace? st]) {
        _emitError(IapFailure('stream_error', 'Purchase stream error',
            details: error, stack: st));
      },
      onDone: () => _subscription.cancel(),
    );

    initStoreInfo();
  }

  @override
  void onClose() {
    if (Platform.isIOS) {
      final iosAddition =
          _iap.getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
      iosAddition.setDelegate(null);
    }
    _subscription.cancel();
    // 兜底：控制器销毁时确保关闭任何遗留遮罩
    _dismissGlobalLoading();
    super.onClose();
  }

  // ===== 日志 & 错误 =====
  void _emitDebug(String msg) => debugPrint('[IAP] $msg');

  void _emitSnack(String title, String msg, {Color bg = Colors.red}) {
    Get.snackbar(title, msg, backgroundColor: bg, colorText: Colors.white);
  }

  void _emitError(IapFailure f) {
    _emitDebug('ERROR: $f\n${f.stack ?? ''}');
    // _emitSnack('payment_failed'.tr, '${f.code}: ${f.message}');
  }

  // ===== 初始化 & 可用性 =====
  Future<void> initStoreInfo() async {
    _loading.value = true;
    try {
      final bool available = await _iap.isAvailable();
      _emitDebug('isAvailable=$available on ${Platform.operatingSystem}');
      if (!available) {
        _isAvailable.value = false;
        _products.clear();
        return;
      }

      // iOS 设置队列代理（支持 Ask to Buy 等）
      if (Platform.isIOS) {
        final iosAddition =
            _iap.getPlatformAddition<InAppPurchaseStoreKitPlatformAddition>();
        // await InAppPurchaseStoreKitPlatform.enableStoreKit1();
        await iosAddition.setDelegate(ExamplePaymentQueueDelegate());
      }

      // 查询商品
      final List<String> _kProductIds =
          Platform.isAndroid ? _googleProductIds : _appleProductIds;
      final ProductDetailsResponse resp =
          await _iap.queryProductDetails(_kProductIds.toSet());
      if (resp.error != null) {
        _queryProductError.value = resp.error!.message;
        _isAvailable.value = false;
        _products.clear();
        _emitDebug(
          'queryProductDetails.error code=${resp.error!.code} '
          'message=${resp.error!.message} details=${resp.error!.details}',
        );
        return;
      }

      if (resp.productDetails.isEmpty) {
        _queryProductError.value = 'No products found';
        _isAvailable.value = false;
        _products.clear();
        _emitDebug(
            'No products returned. Check IDs/console status/region/bundleId.');
        return;
      }

      _products.assignAll(resp.productDetails);
      _isAvailable.value = true;
      _emitDebug(
          'Products: ${_products.map((p) => '${p.id}|${p.title}|${p.price}').join(', ')}');
    } catch (e, st) {
      _isAvailable.value = false;
      _products.clear();
      _emitError(
          IapFailure('init_failed', e.toString(), details: e, stack: st));
    } finally {
      _loading.value = false;
    }
  }

  // ===== 获取所有商品信息 =====
  queryallProducts(googleProducts,appleProducts) async {

        final List<String> requestproductIds =
          Platform.isAndroid ? googleProducts : appleProducts;

      final ProductDetailsResponse resp =
          await _iap.queryProductDetails(requestproductIds.toSet());

      if (resp.error != null) {
     
        return;
      }

      if (resp.productDetails.isEmpty) {
    
        return;
      }

      _products.assignAll(resp.productDetails);
  }

  // ===== 产品 & 价格 =====
  ProductDetails? getProductDetails(String productId) {
    return _products.firstWhereOrNull((p) => p.id == productId);
  }

  Map<String, dynamic>? getProductPriceInfo(String productId) {
    final pd = getProductDetails(productId);
    if (pd == null) return null;
    return {
      'productId': pd.id,
      'price': pd.price, // 本地化字符串
      'rawPrice': pd.rawPrice, // double
      'currencyCode': pd.currencyCode,
      'currencySymbol': pd.currencySymbol,
      'title': pd.title,
      'description': pd.description,
    };
  }

  String formatPrice(String productId) {
    final info = getProductPriceInfo(productId);
    if (info == null) return 'unknown';
    final id = productId.toLowerCase();
    String period;
    if (id.contains('weekly')) {
      period = 'week';
    } else if (id.contains('monthly')) {
      period = 'month';
    } else {
      // 默认使用月订阅
      period = 'month';
    }
    return '${info['price']}/$period'; // 在价格后拼接周期
  }

  List<Map<String, dynamic>> getAllProductPriceInfo() =>
      _products.map((p) => getProductPriceInfo(p.id)!).toList();

  // ===== 购买流程（入口） =====
  Future<void> startSubscriptionPurchase({
    required String productId,
    required int contractId,
    required Function(bool success) onComplete,
  }) async {
    if (_isBuying) {
      _emitDebug('Duplicate click ignored');
      return;
    }
    _isBuying = true;

    // 显示启动购买 loading（不会在此处关闭）
    _showGlobalLoading(message: '正在启动购买…');

    _purchasePending.value = true;
    purchaseCallback.value = onComplete;
    currentContract.value = null;

    try {
      final orderResp = await _paymentService.createOrder(
        productId: productId,
        contarctId: contractId,
      );

      if (!orderResp.isSuccess || orderResp.data == null) {
        _emitDebug('order create failed: ${orderResp.message}');
        _failOnce(IapFailure('Tips', 'order create failed'));
        return;
      }
      currentOrderId.value = orderResp.data!['oid']?.toString();
      if (currentOrderId.value == null) {
        _failOnce(IapFailure('Tips', 'Order not found'));
        return;
      }

      ProductDetails? pd = getProductDetails(productId);
      if (pd == null) {
        final resp = await _iap.queryProductDetails({productId});
        if (resp.productDetails.isEmpty) {
          _failOnce(IapFailure('Tips', 'Product not found'));
          return;
        }
        _products.addAll(resp.productDetails);
        pd = getProductDetails(productId);
        if (pd == null) {
          _failOnce(IapFailure('Tips', 'Product not found'));
          return;
        }
      }

      final purchaseParam = PurchaseParam(
        productDetails: pd,
        applicationUserName:
            Platform.isAndroid ? currentOrderId.value : HttpAgent().androidid,
      );

      await _iap.buyNonConsumable(purchaseParam: purchaseParam);
      // 之后由 purchaseStream 驱动：不要在这里 dismiss loading
    } catch (e, st) {
      _emitDebug('startSubscriptionPurchase exception: $e');
      _failOnce(IapFailure('Tips', 'pay error', details: e, stack: st));
    } finally {
      // 只重置防抖标志；不要 dismiss 全局 loading，
      // 让 _handlePurchasedOnce 在验证结束时负责 dismiss。
      _isBuying = false;
    }
  }

  // ===== 购买更新回调（幂等） =====
  void _onPurchasesUpdated(List<PurchaseDetails> list) {
    for (final pd in list) {
      final key = _purchaseKey(pd);
      _emitDebug(
        'update: key=$key product=${pd.productID} '
        'status=${pd.status} pendingComplete=${pd.pendingCompletePurchase} '
        'purchaseID=${pd.purchaseID}',
      );

      // 恢复流程：收到任何非 pending 状态则关闭加载遮罩
      if (_isRestoringPurchases && pd.status != PurchaseStatus.pending) {
        _isRestoringPurchases = false;
        _dismissGlobalLoading();
      }

      switch (pd.status) {
        case PurchaseStatus.pending:
          _purchasePending.value = true;
          break;
        case PurchaseStatus.purchased:
        case PurchaseStatus.restored:
          _handlePurchasedOnce(key, pd);
          break;
        case PurchaseStatus.error:
          _dismissGlobalLoading();
          _handleErrorOnce(key, pd);
          break;
        case PurchaseStatus.canceled:
          _dismissGlobalLoading();
          _handleCancelOnce(key, pd);
          break;
        default:
          break;
      }
    }
  }

  // 用于区分同一交易的唯一 key（优先 purchaseToken/JWS，其次 purchaseID）
  String _purchaseKey(PurchaseDetails pd) {
    final v = pd.verificationData.serverVerificationData;
    return (v.isNotEmpty
        ? v
        : (pd.purchaseID ?? '${pd.productID}-${pd.hashCode}'));
  }

  Future<void> _handlePurchasedOnce(String key, PurchaseDetails pd) async {
    if (_handledPurchases.contains(key)) {
      await _completeIfNeededOnce(key, pd);
      return;
    }
    _handledPurchases.add(key);

    // 标记正在等待服务端验证（用于图 UI/防重复）
    _pendingServerVerifications.add(key);

    // 启动一个超时的验证流程：若超时则保存到本地并关闭 loading
    bool verified = false;
    try {
      // 构造 payload（回退 localVerificationData 当 serverVerificationData 为空）
      final payload = _buildVerifyPayload(pd);
      String receipt = '';
      if (Platform.isIOS) {
        receipt = payload['receipt-data'] ?? '';
        if (receipt.isEmpty) {
          receipt = pd.verificationData.localVerificationData;
        }
      } else {
        receipt = jsonEncode(payload);
      }

      // 启动实际的验证 Future
      final verifyFuture = _paymentService.verifyPayment(
        orderId: currentOrderId.value ?? '',
        purchaseData: receipt,
      );

      verifyFuture.then((resp) async {
        if (resp.isSuccess) {
          // 验证成功：完成发放
          verified = true;

          _purchasePending.value = false;

          _emitSnack('purchase_success'.tr, 'contract_subscription_success'.tr,
              bg: Colors.green);

          purchaseCallback.value?.call(true);
          // 触发刷新首页等
          try {
            final homeController = Get.find<HomeController>();
            homeController.getHomeData();
          } catch (_) {}
        } else {
          // 超时：保存以便后台/下次启动重试
          // await savePendingPurchaseLocally(pd);
          _emitError(IapFailure('verification_failed', resp.message ?? ''));
          purchaseCallback.value?.call(false);
        }
      }, onError: (e, st) {
        // 超时：保存以便后台/下次启动重试
        // await savePendingPurchaseLocally(pd);
        _emitError(
            IapFailure('verification_failed', '$e', details: e, stack: st));
        purchaseCallback.value?.call(false);
      });
    } catch (e, st) {
      // 异常处理：保存以便重试
      // await savePendingPurchaseLocally(pd);
      _emitError(IapFailure('handle_success_failed', e.toString(),
          details: e, stack: st));
      purchaseCallback.value?.call(false);
    } finally {
      // 无论如何都要 completePurchase（防止重复推送）
      await _completeIfNeededOnce(key, pd);

      // 移除 pending 验证标记
      _pendingServerVerifications.remove(key);

      // 只有在所有 pending 验证都完成（或保存为待重试）时才关闭全局 loading
      if (_pendingServerVerifications.isEmpty) {
        _purchasePending.value = false;
        _dismissGlobalLoading(force: true);
      }
      _clearOrderContext();
    }
  }

  Future<void> _handleErrorOnce(String key, PurchaseDetails pd) async {
    if (_handledPurchases.contains(key)) {
      await _completeIfNeededOnce(key, pd);
      return;
    }
    _handledPurchases.add(key);

    _purchasePending.value = false;
    final err = pd.error;
    _emitDebug(
        'iap_error code=${err?.code} message=${err?.message} details=${err?.details}');
    _emitSnack('payment_failed'.tr, '${err?.code}: ${err?.message}');
    purchaseCallback.value?.call(false);

    await _completeIfNeededOnce(key, pd);
    _pendingServerVerifications.remove(key);
    if (_pendingServerVerifications.isEmpty) {
      _purchasePending.value = false;
      _dismissGlobalLoading(force: true);
    }
    _clearOrderContext();
  }

  Future<void> _handleCancelOnce(String key, PurchaseDetails pd) async {
    if (_handledPurchases.contains(key)) {
      await _completeIfNeededOnce(key, pd);
      return;
    }
    _handledPurchases.add(key);

    _purchasePending.value = false;
    _emitSnack('payment_failed'.tr, 'canceled'.tr);
    purchaseCallback.value?.call(false);

    await _completeIfNeededOnce(key, pd);
    _pendingServerVerifications.remove(key);
    if (_pendingServerVerifications.isEmpty) {
      _purchasePending.value = false;
      _dismissGlobalLoading(force: true);
    }
    _clearOrderContext();
  }

  // ===== 失败统一出口（补全）=====
  void _failOnce(IapFailure f) {
    _dismissGlobalLoading(force: true);
    _purchasePending.value = false;
    _emitError(f);
    purchaseCallback.value?.call(false);
    _clearOrderContext();
  }

  // ===== completePurchase 幂等 =====
  Future<void> _completeIfNeededOnce(String key, PurchaseDetails pd) async {
    if (!pd.pendingCompletePurchase) return;
    if (_completedPurchases.contains(key)) return;

    try {
      await _iap.completePurchase(pd);
      _completedPurchases.add(key);
      // _emitDebug('completePurchase ok for key=$key');
    } catch (e, st) {
      _emitError(
          IapFailure('complete_failed', e.toString(), details: e, stack: st));
    }
  }

  // ===== 校验载荷构造 =====
  Map<String, dynamic> _buildVerifyPayload(PurchaseDetails pd) {
    if (Platform.isIOS) {
       print('iOS receipt===========================: ${pd.purchaseID}');
      return {
        'receipt-data': pd.verificationData.serverVerificationData,
        'password': _appStoreSharedSecret,
        'exclude-old-transactions': true,
        'productId': pd.productID,
        'transactionId': pd.purchaseID,
        'platform': 'ios',
      };
    } else {
      return {
        'orderId': pd.purchaseID,
        'packageName': 'com.company.BitFury', // TODO: 替换为真实包名
        'productId': pd.productID,
        'purchaseTime': '${pd.transactionDate}',
        'purchaseState': pd.status.index,
        'purchaseToken': pd.verificationData.serverVerificationData,
        'quantity': 1,
        'autoRenewing': true,
        'acknowledged': true,
        'platform': 'android',
      };
    }
  }

  // ===== 恢复购买 =====
  Future<void> restorePurchases() async {
    // 开启全局阻断 loading，直到收到购买更新回调
    _showGlobalLoading(message: '正在恢复购买…');

    _isRestoringPurchases = true;

    try {
      await _iap.restorePurchases(); // 结果走 purchaseStream
      _dismissGlobalLoading();
      _emitSnack('restore_success'.tr, 'purchases_restored'.tr,
          bg: Colors.green);
    } catch (e, st) {
      _emitError(
          IapFailure('restore_failed', e.toString(), details: e, stack: st));
      // 出错即关闭遮罩
      _dismissGlobalLoading();
    } finally {
      // 兜底：若平台未返回任何更新事件，5秒后自动关闭
      _dismissGlobalLoading();
    }
  }

  // ===== 辅助 =====
  void _clearOrderContext() {
    currentOrderId.value = null;
    currentContract.value = null; // 一并清理
    purchaseCallback.value = null;
  }

  String _generateObfuscatedAccountId() {
    final userId = UserStorageService().getUserId();
    final bytes =
        utf8.encode(userId ?? '${DateTime.now().millisecondsSinceEpoch}');
    return sha256.convert(bytes).toString();
  }

  // ===== 全局加载遮罩 =====

  void _showGlobalLoading({String message = '处理中，请稍候…'}) {
    // 已经显示就直接返回（防止重复 push）
    if (_globalDialogShowing) return;
    _globalDialogShowing = true;

    // 使用 Get.dialog 并保存 Future 引用
    _dialogFuture = Get.dialog(
      WillPopScope(
        onWillPop: () async => false,
        child: Center(
          child: Container(
            padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 20),
            decoration: BoxDecoration(
              color: Colors.black87,
              borderRadius: BorderRadius.circular(12),
            ),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const SizedBox(
                  width: 40,
                  height: 40,
                  child: CircularProgressIndicator(
                    strokeWidth: 3,
                    valueColor: AlwaysStoppedAnimation<Color>(Colors.white),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
      barrierDismissible: false,
      barrierColor: Colors.black54,
    ).then((_) {
      // 当 dialog 真正被关闭时，重置状态
      _globalDialogShowing = false;
      _dialogFuture = null;
    });
  }

  Future<void> _dismissGlobalLoading({bool force = false}) async {
    // 如果已经认为没有显示，则直接确保状态清理后返回
    if (!_globalDialogShowing && !force) {
      return;
    }

    // 如果 dialogFuture 是 null，可能 dialog 正在创建/尚未 push 到路由栈
    // 我们做最多 5 次短时重试以应对竞态（每次 60ms）
    int attempts = 0;
    while (_globalDialogShowing && attempts < 5) {
      attempts++;
      // 如果 Get 认为有 dialog 打开，优先用 Get.back()
      try {
        if (Get.isDialogOpen == true) {
          // 使用 try/catch 防止抛异常打断流程
          try {
            Get.back();
          } catch (_) {
            // fallback below
          }
        } else {
          // 如果 Get 认为没有打开，但我们的标志显示打开，尝试 Navigator.pop if canPop
          final ctx = Get.context;
          if (ctx != null && Navigator.canPop(ctx)) {
            try {
              Navigator.of(ctx, rootNavigator: true).pop();
            } catch (_) {}
          }
        }
      } catch (_) {}

      // 等个短时间再检查（给 UI 线程机会关闭 dialog）
      await Future.delayed(const Duration(milliseconds: 60));
    }

    // 最后一次保证清理状态
    _globalDialogShowing = false;
    _dialogFuture = null;
  }
}

// ===== iOS 支付队列代理 =====
class ExamplePaymentQueueDelegate implements SKPaymentQueueDelegateWrapper {
  @override
  bool shouldContinueTransaction(
      SKPaymentTransactionWrapper transaction, SKStorefrontWrapper storefront) {
    return true; // 正常继续
  }

  @override
  bool shouldShowPriceConsent() {
    return false;
  }
}
